package cn.myproject.user.controller;

import cn.myproject.user.domian.User;
import cn.myproject.excption.myexcption;
import cn.myproject.user.query.UserQuery;
import cn.myproject.user.service.IUserservice;
import cn.myproject.util.R;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserservice userservice;
    /**
     * 新增用户
     */

    @PostMapping("/add")
    public R inert(@RequestBody User user){
        try {
            userservice.addUser(user);
            return R.ok("登录成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            return R.fail("系统错误，联系工作人员");
        }
    }

    /**
     *修改用户
     * */
    @PostMapping("/updata")
    public R updata(@RequestBody User user){
        try {
            userservice.updata(user);
            return R.ok("修改成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *按id查询用户
     * */
    @PostMapping("/{id}")
    public R<User> selectByid(@PathVariable("id") Long id){
        try {
            User user = userservice.selectByid(id);
            return R.ok(user);
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *分页查询用户
     * */
    @PostMapping("/page")
    public R<PageInfo<User>> selectAll(@RequestBody UserQuery userQuery){
        try {
            PageInfo<User> page= userservice.selectAll(userQuery);
            return R.ok(page);
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *批量删除用户
     * */
    @PostMapping("/deleteall")
    public R<Void> delectall(@RequestBody List<Long> ids){
        try {
            userservice.delectall(ids);
            return R.ok("删除成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return R.fail("系统错误，联系工作人员");
        }
    }
    /**
     *删除用户按id
     * */
    @DeleteMapping("/{id}")
    public R<Void> delectByid(@PathVariable("id") Long id){
        try {
            userservice.delectByid(id);
            return R.ok("删除成功");
        } catch (myexcption e) {
            return R.fail(e.getMessage());
        }catch (Exception e){
            return R.fail("系统错误，联系工作人员");
        }
    }
}
